package com.tedu.ds.coupon.service.impl;

import com.tedu.ds.coupon.mapper.CouponMapper;
import com.tedu.ds.coupon.pojo.dto.CouponQuery;
import com.tedu.ds.coupon.pojo.dto.CouponSaveParam;
import com.tedu.ds.coupon.pojo.entity.Coupon;
import com.tedu.ds.coupon.service.CouponService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    private CouponMapper couponMapper;

    @Scheduled(cron = "0 * * * * ?")
    @Transactional
    public void cleanupExpiredCoupons(){
        CouponQuery query = new CouponQuery();
        query.setStatus("10");
        List<Coupon> coupons = couponMapper.select(query);
        if (!coupons.isEmpty()){
            DateTimeFormatter format=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
            for (Coupon coupon:coupons){
                String[] parts=coupon.getValidityPeriod().split("至");
                LocalDateTime now=LocalDateTime.now();
                LocalDateTime endTime=LocalDateTime.parse(parts[1].trim(),format);
                if (now.isAfter(endTime)){
                    coupon.setStatus("40");
                    couponMapper.update(coupon);
                }
            }
        }
    }

    @Override
    public void save(CouponSaveParam param) {
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(param,coupon);
        if(param.getId()==null){
            couponMapper.save(coupon);
        }else{
            couponMapper.update(coupon);
        }
    }

    @Override
    public void deleteById(Integer id) {
        couponMapper.deleteById(id);
    }

    @Override
    public List<Coupon> select(CouponQuery query) {
        List<Coupon> list = couponMapper.select(query);
        return list;
    }

    @Override
    public void update(CouponSaveParam param) {
        Coupon coupon = new Coupon();
        BeanUtils.copyProperties(param,coupon);
        couponMapper.update(coupon);
    }
}
